﻿<style>
#app {
  height: 100%;
}
</style>
<template>
  <el-container id="app" ref="main_page" style=" border: 1px solid #eee;overflow-x: visible;border: 0;padding-right: 5px;"
                v-loading="isLoading"
                element-loading-text="加载中···">
    <left-menu ref="left_menu" :data="menuList" :menu-config="menuConfig"></left-menu>
    <el-container :style="rightContainerStyle">
      <el-main style="padding:0 0 2px 0px;" ref="main_page">
        <tab-header ref="tabHeader" :menu-item-map="menuItemMap" @tab-remove="handleTabRemove"
                    @tab-refresh="handleTabRefresh"></tab-header>
        <el-row style="padding-top: 10px;padding-left: 10px;">
          <keep-alive :include="cacheComponentNames">
            <router-view  v-if="$store.state.user" :page-height="mainPageHeight" :style="contentStyle"
                          @close-page="closeTab"  @tab-refresh="handleTabRefresh" @tab-active="handleTabActive"
                          :key="$route.fullPath+(cachePathMap[$route.fullPath]?cachePathMap[$route.fullPath].version:'')" />
            <span v-else>正在加载</span>
          </keep-alive>
        </el-row>

      </el-main>
    </el-container>
  </el-container>
<!--  <div id="app" ref="main_page">-->
<!--    <router-view  v-if="$store.state.user" :page-height="mainPageHeight" :style="contentStyle"-->
<!--                  @close-page="closeTab"-->
<!--                  :key="$route.fullPath+(cachePathMap[$route.fullPath]?cachePathMap[$route.fullPath].version:'')" />-->
<!--  </div>-->
</template>
<script>
// import Header from './layout/TopHeader.vue'
// import Breadcrumb from './Breadcrumb.vue'
import TabHeader from './layout/TabHeader.vue'
import LeftMenu from './layout/LeftMenu.vue'
export default {
  name: "MainApp",
  components: {
    // 'top-header': Header,
    // 'ves-breadcrumb': Breadcrumb,
    'tab-header': TabHeader,
    'left-menu': LeftMenu
  },
  data() {
    return {
      menuLoading:false, //菜单加载中标记
      // menuCollapse: false,
      isLoading: false, //数据加载中标记
      //router-view样式
      contentStyle: {
        height: window.innerHeight - 110 + "px",
        overflow: "auto",
      },
      menuList: [],//菜单列表
      menuItemMap: {},//菜单集合
      currentUpdateTask: null,//当前更新任务
      mainPageHeight: window.innerHeight - 110,//主区域页面高度
      //菜单配置
      menuConfig:{
        collapse:false,
        collapseWidth:64,
        minWidth:200,
        maxWidth:200,
        width:200,
        active:''
      },
      //右侧区域样式
      rightContainerStyle:{
        'padding-left':'200px'
      },
      cacheComponentNames:[],//keep-alive缓存路由name数组
      cachePathMap:{},//路径到页面信息映射

    };
  },
  created() {
    // this.loadMenu();
    this.loadUserInfo();
  },
  mounted() {
    this.computePageSize();
  },

  watch: {
    $route(to, from) {
      console.log(to)
      // this.changeBread(to.path);
      if(!this.menuConfig.active&&this.menuItemMap[to.fullPath]) {
        //刷新页面激活菜单项
        this.menuConfig.active = to.fullPath;
      }
      // this.addCacheTab(to);
    },
    menuConfig: {
      handler(val, oldVal) {
        this.rightContainerStyle['padding-left'] = this.menuConfig.width+'px';
      },
      deep: true
    }
  },

  methods: {
    computePageSize() {
      if(!this.$refs["main_page"]) {
        return;
      }
      this.mainPageHeight = this.$refs["main_page"].offsetHeight;
      this.contentStyle.height = this.mainPageHeight + "px";
      window.addEventListener("resize", (event) => {
        if (this.currentUpdateTask) {
          //防止调用频繁
          clearTimeout(this.currentUpdateTask);
        }
        this.currentUpdateTask = setTimeout(() => {
          if (this.$refs["main_page"] == undefined) {
            return;
          }
          this.mainPageHeight = this.$refs["main_page"].offsetHeight - 50;
          this.contentStyle.height = this.mainPageHeight + "px";
          this.currentUpdateTask = null;
        }, 100);
      });
    },
    loadMenu() {
      this.menuLoading = true;
      this.$get("/menu/user/data",{},(response) => {
        this.menuList = response.data;
        function addChildren(menuItem, map) {
          if (menuItem.children && menuItem.children.length > 0) {
            for (let item of menuItem.children) {
              item.parentPath = [];
              for (let p of menuItem.parentPath) {
                item.parentPath.push(p);
              }

              item.parentPath.push(menuItem.path);

              map[item.path] = item;
              addChildren(item, map);
            }
          } else {
            menuItem.leaf = true;
          }
        }

        let map = {};
        for (let item of this.menuList) {
          item.parentPath = [];
          map[item.path] = item;
          addChildren(item, map);
        }
        // map["/todo/list"] = {
        //   parentPath: [],
        //   path: "/todo/list",
        //   name: "事务列表",
        //   leaf: true,
        // };
        this.menuItemMap = map;

      },(response)=>{
        this.menuLoading = false;
      });
    },

    /**
     * 加载用户数据
     */
    loadUserInfo: function () {

      if(window.microApp) {
        const data = window.microApp.getData() // 返回基座下发的data数据
        console.log('基座数据:'+JSON.stringify(data))
        this.$store.commit("updateUser",data.user);
        return;
      }
      this.isLoading = true;
      this.$get("/user/info/current_user", {}, (response) => {
        this.$store.commit("updateUser",response.data);
      }, (response) => {
        this.isLoading = false;
      });
    },
    //新增缓存标签页
    addCacheTab(to){
      //通过路由名称进行查找 （路由名称默认与文件名相同，可以通过$$route name属性设置，不可重复）
      let index = this.cacheComponentNames.indexOf(to.name);
      if(index < 0) {
        this.cacheComponentNames.push(to.name);
        this.cachePathMap[to.fullPath] = {
          name:to.name,
          activeMenu:this.menuConfig.active,
          version:new Date().getTime(),
        };
      } else if(this.cachePathMap[to.fullPath]){
        let activeMenu = this.cachePathMap[to.fullPath].activeMenu;
        if(activeMenu) {
          this.menuConfig.active = activeMenu;
        }
      } else {
        //如果该页面组件已经纳入缓存队列，但是不是该路径触发，则认为该页面有多个访问路径
        this.cachePathMap[to.fullPath] = {
          name:to.name,
          activeMenu:this.menuConfig.active,
          version:new Date().getTime(),
        };
      }
    },
    //处理标签页关闭
    handleTabRemove(path){
      //获取路径缓存信息
      let cacheInfo = this.cachePathMap[path];
      if(cacheInfo){
        //删除路径缓存信息
        Reflect.deleteProperty(this.cachePathMap,path);
        //首先判断缓存的页面里是否有和该路径公用页面的情况，如果有，则不做处理
        for(let key in this.cachePathMap) {
          if(key == path) {
            continue;
          }
          let otherInfo = this.cachePathMap[key];
          if(otherInfo.name==cacheInfo.name) {
            //匹配到其他路径与该路径共用页面，不做后续处理
            return;
          }
        }

        //从keep-alive中移除
        this.cacheComponentNames = this.cacheComponentNames.filter(item=>{
          return cacheInfo.name != item;
        });
      }
    },
    //处理标签页关闭
    handleTabRefresh(path,index){
      // //获取路径缓存信息
      // let cacheInfo = this.cachePathMap[path];
      // if(cacheInfo){
      //   //修改version值，使router-view key更新达到刷新目的
      //   cacheInfo.version=new Date().getTime();
      // }
      this.closeTab(path);
      this.$router.push({path:path},()=>{
        setTimeout(()=>{
          //恢复原来位置
          this.$refs.tabHeader.changeTabIndex(path,index);
        },40)
      });

    },
    //处理激活标签页
    handleTabActive(path){
      this.$refs.tabHeader.activeTab(path);
    },
    //处理关闭标签页事件
    closeTab(path) {
      if(this.$refs.tabHeader) {
        this.$refs.tabHeader.handleTabRemove(path);
      }
    },
  },
};
</script>
